import axios from "axios";
import { request } from "../request";
import { saveAs } from "file-saver";
import {
    UserPrediction,
    ModulePrediction,
    MonthlyWeatherPrediction,
    DailyWeatherPrediction,
    StockPrediction,
    ElectricityPrediction,
} from "@/types/prediction";
import { UserPredictionSearchDto } from "./dto/predict.dto";

export interface WPrediction {
    daily: DailyWeatherPrediction[];
    monthly: MonthlyWeatherPrediction[];
}

export interface SPrediction {
    moutai: StockPrediction[];
    catl: StockPrediction[];
    icbc: StockPrediction[];
}

export const getWeatherPrediction = async (
    timestamp: number
): Promise<ModulePrediction<WPrediction>> => {
    try {
        return await request<ModulePrediction<WPrediction>>(
            "/user/file/get-module-prediction",
            {
                type: "weather",
                date: timestamp,
            }
        );
    } catch (err) {
        throw err;
    }
};

export const getStockPrediction = async (
    timestamp: number
): Promise<ModulePrediction<SPrediction>> => {
    try {
        return await request<ModulePrediction<SPrediction>>(
            "/user/file/get-module-prediction",
            {
                type: "stock",
                date: timestamp,
            }
        );
    } catch (err) {
        throw err;
    }
};

export const getElectricityPrediction = async (
    timestamp: number
): Promise<ModulePrediction<ElectricityPrediction[]>> => {
    try {
        return await request<ModulePrediction<ElectricityPrediction[]>>(
            "/user/file/get-module-prediction",
            {
                type: "electricity",
                date: timestamp,
            }
        );
    } catch (err) {
        throw err;
    }
};

export const getUserPredictions = async (
    page: number,
    size: number,
    condition: Partial<UserPredictionSearchDto>
): Promise<{ count: number; files: UserPrediction[] }> => {
    try {
        return await request<{ count: number; files: UserPrediction[] }>(
            "/user/file/user-prediction-search",
            {
                page: page,
                size: size,
                ...condition,
            }
        );
    } catch (err) {
        throw err;
    }
};

/**
 * 将预测源文件或预测结果数据下载保存到本地
 * @param path 数据路径
 */
export const saveFileToLocal = async (path: string) => {
    try {
        debugger;
        // 发起请求获取文件内容，设置响应类型为 blob
        const res = await axios.get(path, { responseType: "blob" });
        // 从响应头获取文件名
        const contentDisposition = res.headers["content-disposition"];
        let fileName = "downloaded-file";
        if (contentDisposition) {
            const match = contentDisposition.match(
                /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
            );
            if (match != null && match[1]) {
                fileName = match[1].replace(/['"]/g, "");
            }
        }
        // 使用 FileSaver.js 保存文件
        saveAs(res.data, fileName);
    } catch (err) {
        throw err;
    }
};

/**
 * 保存模块预测数据到本地
 * @param data 预测数据
 */
export const saveModulePredictionToLocal = (
    data: SPrediction | ElectricityPrediction[] | []
) => {
    try {
        // 转换为 JSON 字符串
        const jsonData = JSON.stringify(data);
        // 创建 Blob 对象
        const blob = new Blob([jsonData], { type: "application/json" });
        // 使用 FileSaver.js 保存文件
        saveAs(blob, "predictions.json");
    } catch (err) {
        throw err;
    }
};

export const deleteModulePrediction = async (key: string) => {
    try {
        return await request("/user/file/delete-prediction-byKey", {
            key: key,
        });
    } catch (err) {
        throw err;
    }
};

export const deleteUserPrediction = async (id: string) => {
    try {
        return await request("/user/file/delete-user-file", { id: id });
    } catch (err) {
        throw err;
    }
};
